package com.bgi.cg.oss4j.provider.upyun.service;

import cn.hutool.core.util.StrUtil;
import com.bgi.cg.api.AbstractOssService;
import com.bgi.cg.api.entity.OssResponse;
import com.bgi.cg.oss4j.common.util.OssUtil;
import com.bgi.cg.oss4j.provider._base.OssSupplierType;
import com.bgi.cg.oss4j.provider.upyun.RestManagerExt;
import com.bgi.cg.oss4j.provider.upyun.config.UpyunOssConfig;
import com.upyun.RestManager;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Response;

import java.io.File;
import java.util.concurrent.Executor;
import java.util.function.Function;

/**
 * @Description 又拍云
 * @Author Z.cg
 * @Date 2023/9/8
 * @Version 1.0
 **/
@Slf4j
public class UpyunOssService extends AbstractOssService {
    private final UpyunOssConfig config;
    private RestManagerExt client;

    public UpyunOssService(UpyunOssConfig config, Executor pool) {
        super(pool);
        this.config = config;
        client = new RestManagerExt(config.getBucket(), config.getAccessKey(), config.getAccessKeySecret());
        client.setApiDomain(RestManager.ED_AUTO);
    }

    @Override
    public OssResponse upload(File file) {
        return upload(file, config.getBucket());
    }

    @Override
    public OssResponse upload(File file, String bucketName) {
        return upload(file, f -> OssUtil.generatePath(file));
    }

    @Override
    public OssResponse upload(File file, Function<File, String> fileKeyFunction) {
        return upload(file, config.getBucket(), fileKeyFunction);
    }

    /**
     * 上传文件
     * kbEgNlKSe9MhV2PMu2L1Pg0MSKXiSkrC
     *
     * @param file
     * @param fileKeyFunction
     * @return
     */
    public OssResponse upload(File file, String bucket, Function<File, String> fileKeyFunction) {
        valiConfigIsOk();
        // 生成存储的文件名即存储的路径
        String fileName = fileKeyFunction.apply(file);
        OssResponse ossResponse = OssResponse.builder().filePath(fileName).ossType(OssSupplierType.UPYUN.name()).code("0").build();
        try {
            Response response = client.writeFile(bucket, fileName, file, null);
            if (!response.isSuccessful()) ossResponse.setFail(response.message());
        } catch (Exception e) {
            log.error("【{}】文件上传失败：{}", OssSupplierType.UPYUN.name(), e.getMessage());
            ossResponse.setFail(e.getMessage());
        }
        return ossResponse;
    }

    public OssResponse genPreviewUrl(String fileName) {
        return genPreviewUrl(fileName, config.getBucket());
    }

    /**
     * 私有空间 生成预览地址，用于临时预览，下载
     *
     * @param fileName
     * @param bucketName
     * @return
     */
    public OssResponse genPreviewUrl(String fileName, String bucketName) {
        OssResponse ossResponse = OssResponse.builder().code("0").build();
        try {
            String url = OssUtil.getFileDomain(config.getFileDomain(), bucketName) + OssUtil.getRootFileName(fileName);
            ossResponse.setPreviewUrl(url.toString());
        } catch (Exception e) {
            log.error("【{}】文件下载失败：{}", OssSupplierType.UPYUN.name(), e.getMessage());
            ossResponse.setFail(e.getMessage());
        }
        return ossResponse;
    }

    public OssResponse delete(String fileName) {
        return delete(fileName, config.getBucket());
    }

    public OssResponse delete(String fileName, String bucketName) {
        OssResponse ossResponse = OssResponse.builder().code("0").build();
        if (StrUtil.isBlank(bucketName)) return ossResponse.setFail("操作桶不能为空");
        try {
            client.deleteFile(bucketName, fileName, null);
        } catch (Exception e) {
            log.error("【{}】文件删除失败：{}", OssSupplierType.UPYUN.name(), e.getMessage());
            ossResponse.setFail(e.getMessage());
        }
        return ossResponse;
    }

    void valiConfigIsOk() {
        if (!config.configIsOk()) {
            throw new RuntimeException("未配置[accessKey,accessKeySecret,bucket,endPoint,region]值");
        }
    }
}
